//
//  UILayoutView.m
//  HelloWorld
//
//  Created by Mac Book-1 on 10-7-1.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UILayoutView.h"


@implementation UILayoutView

@synthesize autoFitFrame;
@synthesize style;

- (id)initWithFrame:(CGRect)aRect {
    self = [super initWithFrame:aRect];
    if (self) {
		autoFitFrame = YES;
		style = 0;
		iLeftPt = 0;
		iTopPt = 0;
		iVertical = 0;
		iHorizontal = 0;
	}
    return self;
}

- (void)layoutSubviews{
	int count = [self.subviews count];
	UIView* subView = nil;
	CGRect rect;
	CGPoint pt;
	int toalWidth = 0;
	for (int i = 0; i < count; i++) {
		subView = [self.subviews objectAtIndex:i];
		//[subView layoutSubviews];
		rect = [subView bounds];
		toalWidth += rect.size.width;
	}
	toalWidth += interval * (count - 1);
	
	int x = iLeftPt;
	int y = iTopPt;
	
	if (style == 0) {
		switch (iHorizontal) {
			case 1:
				x = iLeftPt;
				break;
			case 0:
				x = (self.bounds.size.width - toalWidth) / 2;
				break;
			case 2:
				x = self.bounds.size.width - toalWidth;
				break;
				
		}
		for (int i = 0; i < count; i++) {
			subView = [self.subviews objectAtIndex:i];
			rect = [subView bounds];
			switch (iVertical) {
				case 1:
					y = iTopPt;
					break;
				case 0:
					y = (self.bounds.size.height - rect.size.height) / 2;
					break;
				case 2:
					y = self.bounds.size.height - rect.size.height;
					break;
			}
			subView.bounds = rect;
			if ([subView isKindOfClass:[CUIControlBase class]]) {
				((CUIControlBase*)subView).iAbsoluteY = self.iAbsoluteY + y;
			}
			pt = CGPointMake(x + rect.size.width / 2, y + rect.size.height / 2);
			
			subView.center = pt;
			x += rect.size.width;
			x += interval;
		}
	}
	else{
		for (int i = 0; i < count; i++) {
			subView = [self.subviews objectAtIndex:i];
			rect = [subView frame];
			switch (iHorizontal) {
				case 1:
					x = iLeftPt;
					break;
				case 0:
					x = (self.bounds.size.width - rect.size.width) / 2;
					break;
				case 2:
					x = self.bounds.size.width - rect.size.width;
					break;

			}
			subView.bounds = rect;
			((UIViewBase*)subView).iAbsoluteY = self.iAbsoluteY + y;
			pt = CGPointMake(x + rect.size.width / 2, y + rect.size.height / 2);
			subView.center = pt;
			y += rect.size.height;
			y += interval;
		}
	}

}

- (void)adjustFrame:(UIView *)view{
	if (autoFitFrame) {
		CGRect rect;
		if (style == 0) {
			if (view.bounds.size.height + iTopPt > self.bounds.size.height) {
				rect = self.bounds;
				rect.size.height = view.bounds.size.height + iTopPt;
				self.bounds = rect;
			}
		}
		else {
			int count = [self.subviews count];
			if (count == 1) {
				rect = self.bounds;
				rect.size.height = view.bounds.size.height + iTopPt;
				self.bounds = rect;
			}
			else {
				rect = self.bounds;
				rect.size.height += iTopPt;
				rect.size.height += view.bounds.size.height;
				self.bounds = rect;
			}
		}
	}
}
- (void)dealloc {
	[super dealloc];
}

@end
